package org.huatek.anders.utils;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.joda.time.DateTime;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.concurrent.*;

/**
 * @author anders
 * @date 2018-12-07 09:18
 **/
public enum IdGenerator {
    /**
     * 单例
     */
    INSTANCE;

    private static Object lockObj = "lockerOrder";
    private static long orderNumCount = 0L;
    private int maxPerMSECSize = 1000;


    public synchronized String getUnionNum(String prefix) {
        String finOrderNum;
        synchronized(lockObj) {
            long nowLong = Long.parseLong(DateTime.now().toString("yyyyMMddSSS"));
            if (orderNumCount >= (long)this.maxPerMSECSize) {
                orderNumCount = 0L;
            }

            String countStr = (long)this.maxPerMSECSize + orderNumCount + "";
            finOrderNum = nowLong + countStr.substring(1);
            ++orderNumCount;
        }

        return prefix + finOrderNum;
    }
    
    public static void main(String[] args){
        Set<String> set = new ConcurrentSkipListSet<>();
        ThreadFactory customThreadfactory = new ThreadFactoryBuilder()
                .setNameFormat("DemoPool-Thread").setDaemon(false)
                .setPriority(Thread.MAX_PRIORITY).build();

        ExecutorService executor = Executors.newFixedThreadPool(10,
                customThreadfactory);

        int cnt = 15;
        for(int i=0;i<cnt;i++){
            executor.execute(()->{
                String no = IdGenerator.INSTANCE.getUnionNum("P");
                set.add(no);
                System.out.println(no);
            });

        }
        executor.shutdown();
        try {
            Thread.sleep(1000L);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        System.out.println(set.size());
    }
}
